<template>
  <div class="permission-container">
    <a-card :bordered="false">
      <template #title>权限管理</template>

      <!-- 操作按钮 -->
      <div class="table-operations">
        <a-space>
          <a-button type="primary" @click="handleAdd" v-if="hasPermission('system:permission:add')">
            <template #icon><plus-outlined /></template>
            新增
          </a-button>
          <a-button @click="expandAll">
            <template #icon><fullscreen-outlined /></template>
            展开全部
          </a-button>
          <a-button @click="collapseAll">
            <template #icon><fullscreen-exit-outlined /></template>
            折叠全部
          </a-button>
        </a-space>
      </div>

      <!-- 权限树形表格 -->
      <a-table
        :columns="columns"
        :data-source="permissionList"
        :loading="loading"
        :pagination="false"
        :row-key="(record: any) => record.permissionId"
        :expandable="{
          defaultExpandAllRows: false,
          expandedRowKeys: expandedKeys
        }"
      >
        <!-- 自定义列 -->
        <template #bodyCell="{ column, record }">
          <!-- 权限类型列 -->
          <template v-if="column.key === 'permissionType'">
            <a-tag :color="getPermissionTypeColor(record.permissionType)">
              {{ getPermissionTypeName(record.permissionType) }}
            </a-tag>
          </template>
          
          <!-- 状态列 -->
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'success' : 'error'">
              {{ record.status === 1 ? '正常' : '禁用' }}
            </a-tag>
          </template>
          
          <!-- 操作列 -->
          <template v-if="column.key === 'operation'">
            <a-space>
              <a @click="handleAdd(record)" v-if="hasPermission('system:permission:add')">新增</a>
              <a-divider type="vertical" />
              <a @click="handleEdit(record)" v-if="hasPermission('system:permission:edit')">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除该权限吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record)"
                v-if="hasPermission('system:permission:delete')"
              >
                <a class="danger-text">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 权限表单对话框 -->
    <permission-form
      v-model:visible="formVisible"
      :form-data="formData"
      @success="handleSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  PlusOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined
} from '@ant-design/icons-vue'
import { usePermission } from '@/composables/usePermission'
import * as permissionApi from '@/api/permission'
import type { SysPermission } from '@/types/permission'
// 不需要TableProps类型
import PermissionForm from './components/PermissionForm.vue'

// 权限检查
const { checkPermission: hasPermission, convertToTree } = usePermission()

// 状态
const loading = ref(false)
const permissionList = ref<any[]>([])
const expandedKeys = ref<number[]>([])
const formVisible = ref(false)
const formData = ref<Partial<SysPermission>>({})

// 无需分页配置，使用树形结构展示所有数据

// 表格列定义
const columns = [
  {
    title: '权限名称',
    dataIndex: 'permissionName',
    key: 'permissionName'
  },
  {
    title: '权限标识',
    dataIndex: 'permissionKey',
    key: 'permissionKey'
  },
  {
    title: '权限类型',
    dataIndex: 'permissionType',
    key: 'permissionType'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime'
  },
  {
    title: '操作',
    key: 'operation',
    width: 220
  }
]

// 初始化
onMounted(() => {
  getPermissionList()
})

// 获取权限列表
const getPermissionList = async () => {
  loading.value = true
  try {
    const res = await permissionApi.getPermissionList()
    
    // 转换为树形结构
    permissionList.value = convertToTree(res)
  } catch (error) {
    console.error('获取权限列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 展开全部
const expandAll = () => {
  const keys: number[] = []
  const getAllIds = (list: any[]) => {
    list.forEach(item => {
      keys.push(item.permissionId)
      if (item.children && item.children.length > 0) {
        getAllIds(item.children)
      }
    })
  }
  getAllIds(permissionList.value)
  expandedKeys.value = keys
}

// 折叠全部
const collapseAll = () => {
  expandedKeys.value = []
}

// 获取权限类型名称
const getPermissionTypeName = (type: number) => {
  switch (type) {
    case 1:
      return '目录'
    case 2:
      return '菜单'
    case 3:
      return '按钮'
    default:
      return '未知'
  }
}

// 获取权限类型颜色
const getPermissionTypeColor = (type: number) => {
  switch (type) {
    case 1:
      return 'purple'
    case 2:
      return 'blue'
    case 3:
      return 'green'
    default:
      return 'default'
  }
}

// 新增权限
const handleAdd = (record?: SysPermission) => {
  formData.value = {
    // 如果是子权限，设置父权限ID
    parentId: record ? record.permissionId : 0,
    permissionType: 2, // 默认为菜单
    status: 1, // 默认正常状态
    isHidden: false,
    sortOrder: 0
  }
  formVisible.value = true
}

// 编辑权限
const handleEdit = (record: SysPermission) => {
  formData.value = { ...record }
  formVisible.value = true
}

// 删除权限
const handleDelete = async (record: SysPermission) => {
  try {
    await permissionApi.deletePermission(record.permissionId)
    message.success('删除成功')
    getPermissionList()
  } catch (error) {
    console.error('删除权限失败:', error)
    message.error('删除失败')
  }
}

// 表单提交成功回调
const handleSuccess = () => {
  formVisible.value = false
  getPermissionList()
}

// 无需表格变化处理函数，因为不使用分页
</script>

<style scoped>
.permission-container {
  padding: 24px;
}

.table-operations {
  margin-bottom: 16px;
}

.danger-text {
  color: #ff4d4f;
}

.danger-text:hover {
  color: #ff7875;
}
</style>
